<template>
    <div id='safetySetting'>
        <ul class='safety-settings'>
            <li v-for='item in safetySettings' :key='item.icon' class='safety-setting-item'>
                <div class='left'>
                    <img :src='item.icon' alt='email'>
                    <span class='label'>{{ item.label }}</span>
                    <span class='content'>{{ item.content || '未设置' }}</span>
                </div>
                <el-button :disabled='item.dev' plain type='primary' @click='item.fn'>修改</el-button>
            </li>
        </ul>
    </div>
    <!--    邮箱设置-->
    <el-dialog
        v-model='mailDialog' :close-on-click-modal='false' title='邮箱设置' width='400'
        @close='closeAllDialogAndResetForm'>
        <el-form ref='formRef' :rules='rules' :model='form' label-width='100' label-position='top'>
            <el-form-item label='邮箱' prop='email'>
                <el-input v-model='form.email' autocomplete='off' placeholder='请输入邮箱' />
            </el-form-item>
            <el-form-item prop='code' class='email-box' label='验证码'>
                <el-input v-model='form.code' placeholder='请输入验证码' />
                <el-button
                    class='getcode' :disabled='sendStateObj.lock'
                    link type='primary' @click='getCodeHandler'>{{ sendStateObj.text }}
                </el-button>
            </el-form-item>
        </el-form>
        <template #footer>
      <span class='dialog-footer'>
        <el-button @click='closeAllDialogAndResetForm'>取消</el-button>
        <el-button type='primary' @click='submitMailChange'>
          确定
        </el-button>
      </span>
        </template>
    </el-dialog>

    <!--    密码设置-->
    <el-dialog
        v-model='passwordDialog' :close-on-click-modal='false' title='密码设置' width='450'
        @close='closeAllDialogAndResetForm'>
        <el-form ref='formRef' :rules='rules' :model='form' label-width='100' label-position='top'>
            <el-form-item label='旧密码' prop='oldPassword'>
                <el-input v-model='form.oldPassword' show-password autocomplete='off' placeholder='请输入旧密码' />
            </el-form-item>
            <el-form-item label='新密码' prop='newPassword'>
                <el-input v-model='form.newPassword' show-password autocomplete='off' placeholder='请输入新密码' />
            </el-form-item>
            <el-form-item label='确认密码' prop='reNewPassword'>
                <el-input v-model='form.reNewPassword' show-password autocomplete='off' placeholder='请确认新密码' />
            </el-form-item>
        </el-form>
        <template #footer>
      <span class='dialog-footer'>
        <el-button @click='closeAllDialogAndResetForm'>取消</el-button>
        <el-button type='primary' @click='submitPwdChange'>
          确定
        </el-button>
      </span>
        </template>
    </el-dialog>
</template>
<script setup lang='ts'>
import { getCurrentInstance, reactive, ref, toRefs } from 'vue';
import emailIcon from '@/assets/my/email.png';
import lockIcon from '@/assets/my/lock.png';
import phoneIcon from '@/assets/my/phone.png';
import wechatIcon from '@/assets/my/wechat.png';
import qqIcon from '@/assets/my/qq.png';
import facebookIcon from '@/assets/my/facebook.png';
import baiduIcon from '@/assets/my/baidu.png';
import useUserStore from '@/store/modules/user';
import { bindMail, getMailCode } from '@/api/business/user';
import { updateUserPwd } from '@/api/system/user';

const user = useUserStore();
const { proxy } = getCurrentInstance();
const mailDialog = ref(false);//邮箱
const passwordDialog = ref(false);//密码

/*发送验证码的按钮状态*/
const sendStateObj = ref<{ sec: number, lock: boolean, timer: any, text: string }>({
    sec: 60,
    lock: false,
    timer: undefined,
    text: '获取验证码'
});
const equalToPassword = (rule: any, value: any, callback: (...args: any[]) => void) => {
    if (form.value.newPassword !== value) {
        callback(new Error('两次输入的密码不一致'));
    } else {
        callback();
    }
};
const data = reactive({
    form: {
        email: user?.userInfo?.email || '',
        code: '',
        oldPassword: '',
        newPassword: '',
        reNewPassword: ''
    },
    rules: {
        email: [{
            required: true, message: '请输入邮箱', trigger: 'blur'
        }, {
            pattern: /^[a-zA-Z0-9._%±]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/, message: '请输入正确的邮箱', trigger: 'blur'
        }],
        code: [{
            required: true, message: '请输入验证码', trigger: 'blur'
        }],
        oldPassword: [{
            required: true, message: '请输入旧密码', trigger: 'blur'
        }, { min: 5, max: 20, message: '旧密码长度必须介于 5 和 20 之间', trigger: 'blur' }]
        ,
        newPassword: [{
            required: true, message: '请输入新密码', trigger: 'blur'
        }, { min: 5, max: 20, message: '新密码长度必须介于 5 和 20 之间', trigger: 'blur' }],
        reNewPassword: [{
            required: true, message: '请确认新密码', trigger: 'blur'
        }, { required: true, validator: equalToPassword, trigger: 'blur' }]
    }
});
const { form, rules } = toRefs(data);
/*打开邮箱*/
const openMailSetting = () => mailDialog.value = true;
/*打开密码*/
const openPasswordSetting = () => passwordDialog.value = true;
const safetySettings = ref([
    {
        fn: () => openMailSetting(),
        icon: emailIcon,
        label: '邮箱',
        content: user.userInfo.email,
        dev: false
    }, {
        fn: () => openPasswordSetting(),
        icon: lockIcon,
        label: '密码',
        content: '已设置',
        dev: false
    }, {
        fn: () => openMailSetting(),
        icon: phoneIcon,
        label: '手机号码',
        content: user.userInfo.phonenumber,
        dev: true
    }, {
        fn: () => openMailSetting(),
        icon: wechatIcon,
        label: '微信',
        content: null,
        dev: true
    }, {
        fn: () => openMailSetting(),
        icon: qqIcon,
        label: 'QQ',
        content: null,
        dev: true
    }, {
        fn: () => openMailSetting(),
        icon: facebookIcon,
        label: '脸书',
        content: null,
        dev: true
    }, {
        fn: () => openMailSetting(),
        icon: baiduIcon,
        label: '百度',
        content: null,
        dev: true
    }
]);
/*修改密码*/
const submitPwdChange = () => {
    proxy.$refs['formRef'].validate((valid: boolean) => {
        if (valid) {
            updateUserPwd(form.value.oldPassword, form.value.newPassword).then(() => {
                proxy.$modal.msgSuccess('密码修改成功!');
                closeAllDialogAndResetForm();
            });
        }
    });
};
/*修改邮箱*/
const submitMailChange = () => {
    proxy.$refs['formRef'].validate((valid: boolean) => {
        if (valid) {
            const obj = {
                title: '绑定邮箱',
                email: form.value.email,
                code: form.value.code
            };
            bindMail(obj).then(() => {
                proxy.$modal.msgSuccess('邮箱绑定成功!');
                user.userInfo.email = obj.email;
                closeAllDialogAndResetForm();
            });
        }
    });
};
/*获取验证码*/
const getCodeHandler = () => {
    //发送验证码API
    const obj: {
        title: string,
        email: string
    } = {
        title: '绑定邮箱',
        email: form.value.email
    };
    getMailCode(obj).then(() => {
        // 调用倒计时函数
        countdown();
        proxy.$modal.msgSuccess('验证码获取成功!');
    });
};
/*倒计时*/
const countdown = () => {
    if (sendStateObj.value.sec <= 0) {
        sendStateObj.value.lock = false;
        sendStateObj.value.text = '重新获取';
        sendStateObj.value.sec = 60;
        clearTimeout(sendStateObj.value.timer);
    } else {
        sendStateObj.value.lock = true;
        sendStateObj.value.timer = setTimeout(() => {
            sendStateObj.value.sec--;
            sendStateObj.value.text = `${sendStateObj.value.sec}秒后重新获取`;
            countdown();
        }, 1000);
    }
};
/*关闭所有弹出层并重置表单*/
const closeAllDialogAndResetForm = () => {
    form.value = {
        email: user?.userInfo?.email || '',
        code: '',
        oldPassword: '',
        newPassword: '',
        reNewPassword: ''
    };
    mailDialog.value = false;
    passwordDialog.value = false;
    proxy.resetForm('formRef');
};
</script>
<style scoped lang='scss'>


.email-box {
    position: relative;

    :deep(.el-input__wrapper) {
        padding-right: 130px;
    }

    .getcode {
        position: absolute;
        top: 50%;
        right: 10px;
        font-size: 16px;
        transform: translateY(-50%);
    }
}

.safety-settings {
    display: flex;
    flex-wrap: wrap;

    .safety-setting-item {
        display: flex;
        align-items: center;
        border: 1px solid #efefef;
        padding: 14px 10px;
        border-radius: 4px;
        margin-bottom: 24px;
        margin-right: 50px;
        width: calc(50% - 25px);
        justify-content: space-between;

        &:nth-child(2n) {
            margin-right: 0;
        }

        .label {
            margin: 0 12px;
            font-size: 18px;
            font-weight: 500;
            color: rgba(0, 0, 0, 0.7);
            width: 100px;
        }

        .content {
            margin-right: 60px;
            font-size: 16px;
            font-weight: 500;
            color: rgba(0, 0, 0, 0.5);
        }

        .left {
            display: flex;
            align-items: center;
        }
    }
}
</style>
